package com.baizhi.service.impl;

import com.baizhi.dao.ProductDao;
import com.baizhi.Sale;
import com.baizhi.product;
import com.baizhi.service.ProductService;
import com.baizhi.util.MyBatisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class ProductServiceImpl implements ProductService {

    @Override
    public List<product> selectAll() {
        SqlSession sqlSession = MyBatisUtils.openSession();
        List<product> all = null;
        try {
            ProductDao mapper = sqlSession.getMapper(ProductDao.class);
            all = mapper.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return  all;
    }

    @Override
    public boolean updateProduct(Sale p, int quantity) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            ProductDao dao = session.getMapper(ProductDao.class);
            dao.update(p);
            dao.updateQuantity(quantity,p.getProductId());
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
       return  true;
    }

    @Override
    public PageInfo<Sale> page(String where ,int pageIndex,int pageSize) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        List<Sale> page=new ArrayList<>();
        try {
            ProductDao mapper = sqlSession.getMapper(ProductDao.class);
            PageHelper.startPage(pageIndex,pageSize);
            page = mapper.page(where);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
         PageInfo<Sale> c=new PageInfo<>(page);
        return  c;
    }

    @Override
    public int kucun(int id) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        int a=0;
        try {
            ProductDao dao = sqlSession.getMapper(ProductDao.class);
            a = dao.kucun(id);
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return a;
    }
}
